package com.etao.restaurantservice.common;



import com.alibaba.fastjson.JSON;
import com.etao.restaurantcore.util.ConfigUtil;
import com.etao.restaurantcore.util.JsonUtil;
import com.etao.restaurantcore.util.email.EmailUtil;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.Map;

/**
 * Created by mike on 2015/12/28.
 */
@Service
public class ApiService {
    //private static Logger logger = LoggerFactory.getLogger(ApiService.class);
    @Autowired
    RestTemplate restTemplate;

    /**
     * Post请求
     *
     * @param url
     * @param t
     * @param <T>
     * @return
     */
    public <T> T apiRequest(String url, Class<T> t) {
        return apiRequestPost(url, t, null);
    }

    /**
     * post请求
     *
     * @param url
     * @param t
     * @param params
     * @param <T>
     * @return
     */
    public <T> T apiRequestPost(String url, Class<T> t, Map<String, ?> params) {
        //logger.info(String.format("请求URL:%s 请求参数:%s", url, JsonUtil.toJson(params)));
        if (url == null || url.isEmpty())
            return null;

        HttpHeaders headers = new HttpHeaders();
        /*headers.set("Content-Type", "application/json");
        headers.set("sign", DigestUtils.md5Hex(ConfigUtil.getInstance().getErpSign()));*/

        HttpEntity httpEntity = new HttpEntity(null, headers);

        try {
            ResponseEntity responseEntity = params != null ? restTemplate.postForEntity(url, httpEntity, t, params) : restTemplate.postForEntity(url, httpEntity, t);
            //logger.info(String.format("请求URL:%s 返回结果:%s", url, responseEntity.toString()));
            if (responseEntity.getStatusCode() == HttpStatus.OK) {
                return (T) responseEntity.getBody();
            } else {
                return null;
            }
        } catch (Exception e) {
            //logger.error("请求接口出错", e);
            EmailUtil.send("请求接口(ErpApi)出错", e.toString());
            return null;
        }
    }

    public <T> T apiRequestPostBody(String url, Class<T> t, String body) {
        //logger.info(String.format("请求URL:%s 请求参数:%s", url, body));
        if (url == null || url.isEmpty())
            return null;

        HttpHeaders headers = new HttpHeaders();
        /*headers.set("Content-Type", "application/json");
        headers.set("sign", DigestUtils.md5Hex(ConfigUtil.getInstance().getErpSign() + body));*/

        HttpEntity httpEntity = new HttpEntity(headers);
        HttpEntity<String> httpEntity1 = new HttpEntity<String>(body, headers);

        try {
            ResponseEntity responseEntity = restTemplate.postForEntity(url, httpEntity1, t);
            //logger.info(String.format("请求URL:%s 返回结果:%s", url, responseEntity.toString()));
            if (responseEntity.getStatusCode() == HttpStatus.OK) {
                return (T) responseEntity.getBody();
            } else {
                return null;
            }
        } catch (Exception e) {
            //logger.error("请求接口出错", e);
            EmailUtil.send("请求接口(ErpApi)出错", e.toString());
            return null;
        }
    }

    /**
     * get请求
     *
     * @param url
     * @param t
     * @param <T>
     * @return
     */
    public <T> T apiRequestGet(String url, Class<T> t) {
        return apiRequestGet(url, t, null);
    }

    public <T> T apiRequestGet(String url, Class<T> t, Map<String, ?> params) {
        //logger.info(String.format("请求URL:%s 请求参数:%s", url, JsonUtil.toJson(params)));
        if (url == null || url.isEmpty())
            return null;

        HttpHeaders headers = new HttpHeaders();
        /*headers.set("Content-Type", "application/json");
        headers.set("sign", DigestUtils.md5Hex(ConfigUtil.getInstance().getErpSign()));*/

        HttpEntity httpEntity = new HttpEntity(null, headers);

        try {
            ResponseEntity responseEntity = params != null ? restTemplate.exchange(url, HttpMethod.GET, httpEntity, t, params) : restTemplate.exchange(url, HttpMethod.GET, httpEntity, t);
            //logger.info(String.format("请求URL:%s 返回结果:%s", url, responseEntity.toString()));
            if (responseEntity.getStatusCode() == HttpStatus.OK) {
                return (T) responseEntity.getBody();
            } else {
                return null;
            }
        } catch (Exception e) {
            //logger.error("请求接口出错", e);
            EmailUtil.send("请求接口(ErpApi)出错", e.toString());
            return null;
        }
    }

    public <T> T apiHttpPost(String url, Class<T> t, String params) {
        //logger.info(String.format("请求URL:%s 请求参数:%s", url, params));
        CloseableHttpClient httpClient = null;
        String result = "";
        try {
            httpClient = HttpClients.createDefault();

            CloseableHttpResponse httpResponse = null;
            HttpPost httpPost = new HttpPost(url);
            /*httpPost.setHeader("sign", DigestUtils.md5Hex(ConfigUtil.getInstance().getErpSign() + (params == null ? "" : params)));
            httpPost.setHeader("Content-Type", "application/json");*/

            if (params != null) {
                StringEntity entity = new StringEntity(params, "utf-8");
                entity.setContentEncoding("UTF-8");
                httpPost.setEntity(entity);
            }

            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(5000).build();//设置请求和传输超时时间
            httpPost.setConfig(requestConfig);

            httpResponse = httpClient.execute(httpPost);
            try {
                if (httpResponse.getStatusLine().getStatusCode() == 200) {
                    result = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
                    //logger.info(String.format("请求URL:%s 返回结果:%s", url, result));
                }
            } catch (IOException e) {
                //logger.error(String.format("请求URL:%s 解析结果出错", url), e);
                return null;
            } finally {
                httpResponse.close();
            }
        } catch (Exception e) {
            //logger.error(String.format("请求URL:%s 请求接口出错", url), e);
            // EmailUtil.send("请求接口(ErpApi)出错", e.toString());
        } finally {
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {

                }
            }
        }

        try {
            return (T) JSON.parseObject(result, t);
        } catch (Exception e) {
            //logger.error(String.format("请求URL:%s 解析结果出错:%s", url, result), e);
            // EmailUtil.send("解析结果出错", result + "\r\n" + e.toString());
            return null;
        }
    }

    /**
     * 传递一个List集合，List没有class属性
     * @param url
     * @param t
     * @param params
     * @param <T>
     * @return
     */
    public <T> T apiHttpPost(String url, T t, String params) {
        //logger.info(String.format("请求URL:%s 请求参数:%s", url, params));
        CloseableHttpClient httpClient = null;
        String result = "";
        try {
            httpClient = HttpClients.createDefault();

            CloseableHttpResponse httpResponse = null;
            HttpPost httpPost = new HttpPost(url);
            /*httpPost.setHeader("sign", DigestUtils.md5Hex(ConfigUtil.getInstance().getErpSign() + (params == null ? "" : params)));
            httpPost.setHeader("Content-Type", "application/json");*/

            if (params != null) {
                StringEntity entity = new StringEntity(params, "utf-8");
                entity.setContentEncoding("UTF-8");
                httpPost.setEntity(entity);
            }

            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(5000).build();//设置请求和传输超时时间
            httpPost.setConfig(requestConfig);

            httpResponse = httpClient.execute(httpPost);
            try {
                if (httpResponse.getStatusLine().getStatusCode() == 200) {
                    result = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
                    //logger.info(String.format("请求URL:%s 返回结果:%s", url, result));
                }
            } catch (IOException e) {
                //logger.error(String.format("请求URL:%s 解析结果出错", url), e);
                return null;
            } finally {
                httpResponse.close();
            }
        } catch (Exception e) {
            //logger.error(String.format("请求URL:%s 请求接口出错", url), e);
            // EmailUtil.send("请求接口(ErpApi)出错", e.toString());
        } finally {
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                }
            }
        }

        try {
            return (T) JSON.parseObject(result, t.getClass());
        } catch (Exception e) {
            //logger.error(String.format("请求URL:%s 解析结果出错:%s", url, result), e);
            // EmailUtil.send("解析结果出错", result + "\r\n" + e.toString());
            return null;
        }
    }
}